package com.scqzy.shengchunqiang.sword2offer.day20;

import com.scqzy.shengchunqiang.structure.TreeNode;

import java.util.Arrays;

/**
 * @Description: 剑指 Offer 07. 重建二叉树
 * @Author 盛春强
 * @Date 2021/8/27 22:47
 */
public class BuildTree {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) {
            return null;
        }
        int rootVal = preorder[0];
        int p = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (rootVal == inorder[i]) {
                p = i;
                break;
            }
        }
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(Arrays.copyOfRange(preorder, 1, p + 1), Arrays.copyOfRange(inorder, 0, p));
        root.right = buildTree(Arrays.copyOfRange(preorder, p + 1, preorder.length), Arrays.copyOfRange(inorder, p + 1, inorder.length));
        return root;
    }
}
